import request from '@/utils/request'
import { BASE_URL } from '@/utils/config'

// 获取所有动态（广场）
export function getAllPosts(params = {}) {
  return request({
    url: '/posts',
    method: 'GET',
    params: {
      page: params.page || 1,
      pageSize: params.pageSize || 10,
      orderBy: params.orderBy || 'latest',
      user_id: params.userId || 0
    }
  })}

// 获取用户动态
export function getUserPosts(userId) {
  return request({
    url: `/posts/user/${userId}`,
    method: 'GET'
  })
}

// 获取最近动态
export function getRecentPosts(limit = 5) {
  return request({
    url: '/posts/recent',
    method: 'GET',
    params: { limit }
  })
}

// 创建动态
export function createPost(data) {
  const userId = uni.getStorageSync('userId')
  // 检查userId是否存在
  if (!userId) {
    uni.showToast({ title: '请先登录', icon: 'error' });
    return Promise.reject(new Error('用户未登录'));
  }
  const parsedUserId = parseInt(userId);
  if (isNaN(parsedUserId) || parsedUserId <= 0) {
    uni.showToast({ title: '用户ID无效', icon: 'error' });
    return Promise.reject(new Error('无效的用户ID'));
  }
  // 输出调试日志
  console.log('发布动态，用户ID:', parsedUserId);
  return request({
    url: '/posts',
    method: 'POST',
    data: {
      ...data,
      user_id: parsedUserId
    }
  })
}

// 删除动态
export function deletePost(postId) {
  return request({
    url: `/posts/${postId}`,
    method: 'DELETE'
  })
}

// 点赞动态
export function likePost(postId) {
  const userId = uni.getStorageSync('userId') || 0;
  return request({
    url: `/posts/${postId}/like?user_id=${userId}`,
    method: 'POST'
  })}

// 获取动态评论
export function getPostComments(postId) {
  return request({
    url: `/posts/${postId}/comments`,
    method: 'GET'
  })
}

// 添加评论
export function addComment(postId, data) {
  return request({
    url: `/posts/${postId}/comments`,
    method: 'POST',
    data
  })
}

// 获取动态列表
export function getPostList(params = {}) {
  return request({
    url: '/posts',
    method: 'GET',
    params
  })
}

// 获取我的动态
export function getMyPosts() {
  const userId = uni.getStorageSync('userId')
  return getUserPosts(userId)
}

// 获取指定用户的所有动态
export function getPostsByUserId(userId, params) {
  return request({
    url: `/posts/user/${userId}`,
    method: 'GET',
    params
  })
}